const { response } = require("./res");
const jwt = require("jsonwebtoken");

// 密钥，用于签署 JWT
const SECRET_KEY = "yami";

let unprotectedRoutes = []; // 不需要验证的路由

function setUnprotectedRoutes(list) {
  unprotectedRoutes = list;
}

function generateToken(payload) {
  return jwt.sign(payload, SECRET_KEY, { expiresIn: "1h" });
}

function verifyToken(ctx, next) {
  if (unprotectedRoutes.includes(ctx.path)) {
    return next();
  }

  const token = ctx.headers["authorization"];
  if (!token) {
    ctx.status = 401;
    ctx.body = response(false, "Authorization token is required");
    return;
  }

  try {
    const decoded = jwt.verify(token, SECRET_KEY);
    ctx.state.user = decoded;
    return next();
  } catch (err) {
    ctx.status = 401;
    ctx.body = response(false, "Invalid token");
  }
}

module.exports = {
  generateToken,
  verifyToken,
  setUnprotectedRoutes,
};
